from django.shortcuts import render
from rest_framework import viewsets
from rest_framework import mixins
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication


from .models import UserFav, UserLeavingMessage, UserAddress
from .serializers import UserFavSerializer, UserFavDetailSerializer, LeavingMessageSerializer, AddressSerializer


class UserFavViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin,mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin):
    """
    用户收藏
    """
    serializer_class = UserFavSerializer
    # 指定权限认证
    permission_classes = (IsAuthenticated,)
    # token局部验证
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)
    # 指定收藏表的字段
    lookup_field = 'goods_id'


    def get_queryset(self):
        """
        重写queryset方法，只返回自己收藏的商品
        :return:
        """
        return UserFav.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        """
        动态指定序列化器
        :return:
        """
        if self.action == "list":
            return UserFavDetailSerializer
        elif self.action == "create":
            return UserFavSerializer
        return UserFavSerializer


class LeavingMessageViewSet(mixins.CreateModelMixin,mixins.ListModelMixin,mixins.DestroyModelMixin,viewsets.GenericViewSet):
    """
    list:
        用户留言功能
    create:
        添加留言
    delete:
        删除留言
    """
    # 指定序列化器
    serializer_class = LeavingMessageSerializer
    # 指定权限认证
    permission_classes = [IsAuthenticated,]
    # token局部验证
    authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication]

    def get_queryset(self):
        """
        重写queryset方法，只返回当前用户留言
        :return:
        """
        return UserLeavingMessage.objects.filter(user=self.request.user)



class AddressViewset(viewsets.ModelViewSet):
    """
    收货地址管理
    list:
        获取收货地址
    create:
        添加收货地址
    update:
        更新收货地址
    delete:
        删除收货地址
    """
    permission_classes = [IsAuthenticated,]
    authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication]
    serializer_class = AddressSerializer

    def get_queryset(self):
        return UserAddress.objects.filter(user=self.request.user)